package cas.ihep.hadoop.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.Service4Hep;

import java.io.File;
import java.io.IOException;

public class HdfsFileCloserMc extends HdfsFileCloser{

    private static final Log LOG= LogFactory.getLog(HdfsFileCloserMc.class);

    public String cpfile;

    public HdfsFileCloserMc(DFSClient dfsClient, Service4Hep service4Hep, String outfile) throws IOException {
        super(dfsClient, service4Hep, outfile);
    }

    public void close()throws IOException {
        rfs.remove(outputFile);
        File file=new File(opath);
        if(file.exists()){
            long length=file.length();
            File target=new File(cpfile);
            for(int cnt=0;!file.renameTo(target);cnt++){
                LOG.info("Renaming file from "+opath+" to "+cpfile);
                if(cnt>=10){
                    throw new IOException("Time out for renaming file ");
                }
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException ignored){}
            }
            lb.getBlock().setNumBytes(length);
            s4h.calculatefileCheckSums(cpfile,lb);
            s4h.close(lb,outputFile,hfstatus.getFileId());
        }
    }
}
